package com.shoplink.launcher;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.shoplink.view.FocusLayout;

public class MyAppActivity extends Activity {

	private GridView appList;
	private List<AppBean> list = new ArrayList<AppBean>();
	private FocusLayout focusLayout;
	private List<ResolveInfo> mAllApps;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.my_app_layout);
		appList = (GridView) findViewById(R.id.app_list);
		getApkInfo();

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			focusLayout.addFocusView(false);
			View view = appList.getChildAt(0);
			focusLayout.onFocusChange(view, true);
			doAnim(((ViewGroup) view).getChildAt(0), view.getWidth(),
					view.getHeight(), true);
			tempView = ((ViewGroup) view).getChildAt(0);
		};
	};

	AnimatorSet set;
	public void doAnim(View fView, int w, int h, boolean isCom) {

//		if (set == null) {
//			
//		} else {
//			set.end();
//		}
		set = new AnimatorSet();
		if (isCom) {
			ObjectAnimator animatorH = ObjectAnimator.ofInt(fView, "h",
					fView.getHeight(), h);
			ObjectAnimator animatorW = ObjectAnimator.ofInt(fView, "w",
					fView.getWidth(), w);
			set.playTogether(animatorW, animatorH);
			set.setInterpolator(new AccelerateDecelerateInterpolator());
			set.setDuration(300);
			set.start();
		} else {
			ObjectAnimator animatorH = ObjectAnimator.ofInt(fView, "h",
					fView.getHeight(), 0);
			ObjectAnimator animatorW = ObjectAnimator.ofInt(fView, "w",
					fView.getWidth(), 0);
			set.playTogether(animatorW, animatorH);
			set.setInterpolator(new AccelerateDecelerateInterpolator());
			set.setDuration(300);
			set.start();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
	}

	static class ViewHolder {
		ImageView appIcon;
		TextView appName;
	}

	private class MyAdapter extends BaseAdapter {

		LayoutInflater layoutInflater;

		public MyAdapter() {
			// TODO Auto-generated constructor stub
			layoutInflater = LayoutInflater.from(getApplicationContext());
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int positon) {
			return list.get(positon);
		}

		@Override
		public long getItemId(int positon) {
			return 0;
		}

		@Override
		public View getView(int positon, View converView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (converView == null) {
				viewHolder = new ViewHolder();
				converView = layoutInflater.inflate(R.layout.app_itme, null);
				viewHolder.appIcon = (ImageView) converView
						.findViewById(R.id.app_icon);
				viewHolder.appName = (TextView) converView
						.findViewById(R.id.app_name);
				// converView.setOnClickListener(mOnClick);
				converView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) converView.getTag();
			}
			AppBean appBean = list.get(positon);

			viewHolder.appName.setText(appBean.getAppName());
			viewHolder.appIcon.setImageDrawable(appBean.getAppIcon());
			LayoutParams layoutParams = new LayoutParams(234, 234);
			converView.setLayoutParams(layoutParams);
			return converView;
		}
	}

	public List<AppBean> getAllApk() {
		List<AppBean> appBeanList = new ArrayList<>();
		AppBean bean = null;
		PackageManager packageManager = this.getPackageManager();
		List<PackageInfo> list = packageManager.getInstalledPackages(0);
		for (PackageInfo p : list) {
			bean = new AppBean();
			bean.setAppIcon(p.applicationInfo.loadIcon(packageManager));
			bean.setAppName(packageManager.getApplicationLabel(
					p.applicationInfo).toString());
			bean.setAppPackageName(p.applicationInfo.packageName);
			bean.setAppclasseName(p.applicationInfo.className);
			bean.setApkPath(p.applicationInfo.sourceDir);
			File file = new File(p.applicationInfo.sourceDir);
			bean.setAppSize((int) file.length());
			int flags = p.applicationInfo.flags;

			String name = packageManager.getApplicationLabel(p.applicationInfo)
					.toString();
			// 判断是否是属于系统的apk
			if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
				bean.setSystem(true);
				if (name.equals("浏览器") || name.equals("媒体播放器")
						|| name.equals("媒体中心") || name.equals("文件管理器")
						|| name.equals("音乐") || name.equals("音乐")
						|| name.startsWith("Mir")) {
					appBeanList.add(bean);
				}
			} else {
				bean.setSd(true);
				if (!bean.getAppPackageName().startsWith("com.shoplink")) {
					appBeanList.add(bean);
				}

			}

		}
		return appBeanList;
	}

	private void getApkInfo() {

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... arg0) {
				// TODO Auto-generated method stub
				PackageManager mPackageManager = MyAppActivity.this
						.getPackageManager();
				Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
				mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
				mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
				// 按报名排序
				Collections.sort(mAllApps,
						new ResolveInfo.DisplayNameComparator(mPackageManager));
				for (int i = 0; i < mAllApps.size(); i++) {

					AppBean appBean = new AppBean();
					String name = mAllApps.get(i).loadLabel(mPackageManager)
							.toString();
					if (TextUtils.isEmpty(name)) {
						continue;
					}
					Log.d("APP", "===>" + name);
					appBean.setAppName(name);
					appBean.setAppIcon(mAllApps.get(i)
							.loadIcon(mPackageManager));
					appBean.setAppPackageName(mAllApps.get(i).activityInfo.packageName);
					appBean.setAppclasseName(mAllApps.get(i).activityInfo.name);
					if (mAllApps.get(i).system) {
						if (name.equals("浏览器") || name.equals("媒体播放器")
								|| name.equals("媒体中心") || name.equals("文件管理器")
								|| name.equals("音乐") || name.equals("音乐")
								|| name.startsWith("Mir")) {
							list.add(appBean);
						}
					} else {
						if (!mAllApps.get(i).activityInfo.packageName
								.startsWith("com.shoplink")) {
							list.add(appBean);
						}
					}
				}

				return null;
			}

			protected void onPostExecute(Void result) {

				appList.setAdapter(new MyAdapter());
				focusLayout = (FocusLayout) findViewById(R.id.focus_layout);
				appList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						if (list != null) {
							String pkg = list.get(arg2).getAppPackageName();
							String cls = list.get(arg2).getAppclasseName();
							ComponentName componet = new ComponentName(pkg, cls);
							Intent i = new Intent();
							i.setComponent(componet);
							startActivity(i);
						}
					}

				});
				appList.setOnItemSelectedListener(listener);
				handler.sendEmptyMessageDelayed(0, 300);

			};
		}.executeOnExecutor(Executors.newCachedThreadPool());
		// 应用过滤条件

	}

	private View tempView;

	OnItemSelectedListener listener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub

			if (arg1 != null) {
				if (tempView != null) {
					doAnim(tempView, tempView.getWidth(), tempView.getHeight(),
							false);
				}
				focusLayout.onFocusChange(arg1, true);
				doAnim(((ViewGroup) arg1).getChildAt(0), arg1.getWidth(),
						arg1.getHeight(), true);
				tempView = ((ViewGroup) arg1).getChildAt(0);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	};
}
